import { Injectable, signal, computed, inject, effect } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter, map, startWith } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
import { MenuSection, menuSections } from '@shared/models/menu.models';

/**
 * 菜单服务 - 管理应用菜单状态和导航
 * - Signals: 内部状态管理、计算属性、UI 状态
 * - RxJS: 异步操作、事件监听、外部数据流
 */
@Injectable({
  providedIn: 'root'
})
export class MenuService {
  // 路由服务注入 - 用于监听路由变化
  private router = inject(Router);

  // === Signals 状态管理层 ===
  
  // 菜单配置数据源 - 存储所有菜单项的完整配置
  private menuSectionsSignal = signal<MenuSection[]>(menuSections);
  
  // 展开状态管理 - 记录当前展开的菜单项路径数组
  private openedMenuSectionsSignal = signal<string[]>([]);
  
  // === 计算属性层 - 响应式派生状态 ===
  
  // 公开的菜单数据 - 供组件直接访问的菜单配置
  menuSections = computed(() => this.menuSectionsSignal());
  
  // 当前展开的菜单项 - 用于控制侧边栏菜单的展开状态
  openedMenuSections = computed(() => this.openedMenuSectionsSignal());
  
  // 扁平化菜单链接 - 将所有层级的链接菜单项展平为一维数组
  allMenuLinks = computed(() => this.flattenMenuLinks(this.menuSections()));
  
  // 扁平化菜单项 - 将所有层级的菜单项展平为一维数组
  allMenuSections = computed(() => this.flattenMenuSections(this.menuSections()));
  
  // 菜单项映射表 - 提供 O(1) 时间复杂度的菜单项查找
  private menuSectionMap = computed(() => {
    const map = new Map<string, MenuSection>();
    this.menuSections().forEach(section => {
      map.set(section.id, section);
      if (section.pages) {
        section.pages.forEach(page => {
          map.set(page.id, page);
        });
      }
    });
    return map;
  });

  // === RxJS 异步操作层 ===
  
  // 路由变化事件流 - 监听用户导航行为，用于自动更新菜单状态
  private routerEvents$ = this.router.events.pipe(
    filter(event => event instanceof NavigationEnd), // 只监听路由完成事件
    map(event => (event as NavigationEnd).url),     // 提取 URL 路径
    startWith(this.router.url)                       // 提供初始 URL 值
  );

  // 当前 URL 状态 - 将路由事件流转换为响应式状态
  currentUrl = toSignal(this.routerEvents$, { initialValue: this.router.url });

  constructor() {
    // 响应式副作用 - 当 URL 变化时自动更新菜单展开状态
    effect(() => {
      const url = this.currentUrl();
      this.updateOpenedMenuSections(url);
    });
  }

  // === 核心业务逻辑层 ===

  /**
   * 更新菜单展开状态 - 根据当前 URL 自动展开对应的菜单项
   * @param url 当前路由 URL
   */
  private updateOpenedMenuSections(url: string): void {
    const sections = this.menuSections();
    const openedSections: string[] = [];

    sections.forEach(section => {
      if (section.type === 'toggle' && url.startsWith(section.path)) {
        openedSections.push(section.path);
        section.opened = true;
      } else if (section.type === 'toggle') {
        section.opened = false;
      }
    });

    this.openedMenuSectionsSignal.set(openedSections);
  }

  /**
   * 递归扁平化菜单链接 - 提取所有可点击的链接菜单项
   * @param sections 菜单项数组
   * @returns 扁平化的链接菜单项数组
   */
  private flattenMenuLinks(sections: MenuSection[]): MenuSection[] {
    const result: MenuSection[] = [];
    
    for (const section of sections) {
      if (section.type === 'link') {
        result.push(section);
      }
      if (section.pages && section.pages.length) {
        result.push(...this.flattenMenuLinks(section.pages));
      }
    }
    
    return result;
  }

  /**
   * 递归扁平化菜单项 - 将所有层级的菜单项展平为一维数组
   * @param sections 菜单项数组
   * @returns 扁平化的菜单项数组
   */
  private flattenMenuSections(sections: MenuSection[]): MenuSection[] {
    const result: MenuSection[] = [];
    
    for (const section of sections) {
      result.push(section);
      if (section.pages && section.pages.length) {
        result.push(...this.flattenMenuSections(section.pages));
      }
    }
    
    return result;
  }

  // === 公共 API 层 - 组件交互接口 ===

  /**
   * 获取完整菜单配置 - 返回所有菜单项的层级结构
   * @returns 菜单配置数组
   */
  getAllMenuSections(): MenuSection[] {
    return this.menuSections();
  }

  /**
   * 根据 ID 查找菜单项 - 提供 O(1) 时间复杂度的快速查找
   * @param id 菜单项唯一标识符
   * @returns 对应的菜单项或 undefined
   */
  getMenuSectionById(id: string): MenuSection | undefined {
    return this.menuSectionMap().get(id);
  }

  /**
   * 获取所有可点击的菜单链接 - 用于面包屑导航等场景
   * @returns 扁平化的链接菜单项数组
   */
  getAllMenuLinks(): MenuSection[] {
    return this.allMenuLinks();
  }

  /**
   * 获取所有菜单项（扁平化） - 用于搜索、权限检查等场景
   * @returns 扁平化的菜单项数组
   */
  getAllMenuSectionsFlat(): MenuSection[] {
    return this.allMenuSections();
  }


  /**
   * 切换菜单项展开状态 - 用于用户手动控制菜单展开/收起
   * @param id 菜单项唯一标识符
   */
  toggleMenuSection(id: string): void {
    const section = this.getMenuSectionById(id);
    if (section && section.type === 'toggle') {
      section.opened = !section.opened;
      // 触发 Signals 更新，通知所有订阅者
      this.menuSectionsSignal.set([...this.menuSections()]);
    }
  }

  /**
   * 更新完整菜单配置 - 用于动态加载菜单或权限变更
   * @param sections 新的菜单配置数组
   */
  updateMenuSections(sections: MenuSection[]): void {
    this.menuSectionsSignal.set(sections);
  }

  /**
   * 添加单个菜单项 - 用于动态菜单管理
   * @param section 要添加的菜单项
   */
  addMenuSection(section: MenuSection): void {
    const currentSections = this.menuSections();
    this.menuSectionsSignal.set([...currentSections, section]);
  }

  /**
   * 移除指定菜单项 - 用于动态菜单管理
   * @param id 要移除的菜单项 ID
   */
  removeMenuSection(id: string): void {
    const currentSections = this.menuSections();
    const filteredSections = currentSections.filter(section => section.id !== id);
    this.menuSectionsSignal.set(filteredSections);
  }

}